using System;
using System.Collections.Generic;
using Quartz;
using Quartz.Impl;

namespace Accona.Monitoring
{
    public class Schedule 
    {
        private readonly List<Action> _actions = new List<Action>();

        public Schedule(int milliseconds)
        {
            var factory = new StdSchedulerFactory();
            var scheduler = factory.GetScheduler();
            scheduler.Start();
            var jobDetail = new JobDetail("job", null, typeof (ScheduledJob));
            jobDetail.JobDataMap.Add("actions",_actions);

            scheduler.ScheduleJob(jobDetail,
                                  TriggerUtils.MakeImmediateTrigger("NewTrigger", -1, new TimeSpan(0, 0, 0, 0, milliseconds)));
        }

        public void AddAction(Action action)
        {
            _actions.Add(action);
        }

        public class ScheduledJob : IJob
        {
            public void Execute(JobExecutionContext context)
            {
                var actions = context.MergedJobDataMap["actions"] as List<Action>;
                actions.ForEach(a => a());
            }
        }
    }
}